Document

Documents are a structure composed of file and value pairs, similar to JSON objects or other mapping data types. Data in MongoDB is stored in form of documents. These documents are stored in Collection and Collection is stored in Database.

Document Structure
MongoDB documents are composed of field-and-value pairs and have the following structure:
{
   field1: value1,
   field2: value2,
   field3: value3,
   ...
   fieldN: valueN
}

The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents. For example, the following document contains values of varying types:

var mydoc =
          {
               _id: ObjectId("5099803df3f4948bd2f98391"),
               name: { first: "Alan", last: "Turing" },
               birth: new Date('Jun 23, 1912'),
               death: new Date('Jun 07, 1954'),
               contribs: [ "Turing machine", "Turing test", "Turingery" ],
               views : NumberLong(1250000)
            }

The above fields have the following data types:
  • _id holds an ObjectId.
  • name holds an embedded document that contains the fields first and last.
  • birth and death hold values of the Date type.
  • contribs holds an array of strings.
  • views holds a value of the NumberLong type.

Creating the Collection on the fly
The cool thing about MongoDB is that you need not to create collection before you insert document in it. With a single command you can insert a document in the collection and the MongoDB creates that collection on the fly.

Syntax: db.collection_name.insert({key:value, key:value…})
This command will create the collection named “student” on the fly and insert a document in it with the specified key and value pairs.

use dwdev
switched to db dwdev

db.students.insert({
  name: "Devi",
  age: 32,
  add: "Delhi"
})

To check that collection is created successfully.

show collections;
To check whether the document is successfully inserted, type the following command. It shows all the documents in the given collection.

Syntax: db.collection_name.find()

Insert Documents
db.collection_name.insert()

db.students.insert( 
   { 
     name: "Chaitanya", 
     age: 30,
     add: "Hyderabad",
     course: [ { name: "MongoDB", duration: 7 }, { name: "Java", duration: 30 } ]
   } 
)

db.students.find()

Insert Multiple Documents in collection
var beginners =
 [
    {
    "StudentId" : 1001,
    "StudentName" : "Steve",
        "age": 30
    },
    {
    "StudentId" : 1002,
    "StudentName" : "Negan",
        "age": 42
    },
    {
    "StudentId" : 3333,
    "StudentName" : "Rick",
        "age": 35
    },
];
db.students.insert(beginners);

Query Document using find() method
db.students.find()
db.students.find().forEach(printjson);

No comments:

Post a Comment